<?php
/**
 * User: 五哥派
 * Date: 2024/7/17
 * Tel(同WX): 17335592719
 */
namespace app\api\service\auth;

use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\user\User as UserModel;
use app\api\service\BaseService;
use app\api\service\auth\Party as PartyService;
use app\common\lib\exception\BaseException;

use think\Cache;

class Login extends BaseService
{

    /**
     * 用户信息 (登录成功后才记录)
     * @var UserModel|null $userInfo
     */
    private $userInfo;
    private $token;

    const TOKEN_SALT = 'AO9IFEEONVwoneoddfein';

    private $token_expire_in = 7000;//7200 缓存时间

    /**
     * 验证token值
     * @param $token
     * @return bool
     */
    public static function verifyMpWxToken($token){
        $exist = Cache::get($token);

        if($exist){
            return true;
        } else{
            return false;
        }
    }

    public function loginMpWx(array $form): bool
    {

        // 获取微信小程序登录态(session)
        $wxSession = PartyService::getMpWxSession($form['code']);
        $openId = $wxSession['openid'];
        // 获取用户信息
        $userInfo = UserModel::detail(['open_id' => $wxSession['openid']]);

        // 用户信息存在, 更新登录信息。用户不存在: 创建一个新用户
        if(!empty($userInfo)) {
            $this->updateUser($userInfo);
        }else{
            $this->createUser($openId);
        }

        $avatar = $userInfo['avatar'];
        if($avatar && (strpos($avatar, 'thumb_') !== false)){
            $userInfo['avatar'] = config('setting.domain_prefix').config('setting.image_prefix').'avatar/'.$avatar;
        }

        $userId = $this->userInfo->id;
        // 推荐人ID
        $refereeId = $form['refereeId'] ?? null;
        // 记录推荐人关系 绑定推荐关系
        $refereeId > 0 && RefereeModel::createRelation($userId, (int)$refereeId);

        $cachedValue = $this->prepareCachedValue($wxSession, $userId);
        $this->token = $this->saveToCache($cachedValue);
        return true;
    }


    /**
     * 当前登录的用户信息
     * @return UserModel
     */
    public function getUserInfo(): UserModel
    {
        return $this->userInfo;
    }


    /**
     * 获取登录的token
     * @return string
     */
    public function getToken(): string
    {
        return $this->token;
    }

    public function createUser($openId){
        // 用户信息
        $data = [
            'open_id' => $openId,
            'login_time' => time(),
        ];

        // 新增用户记录
        $model = new UserModel;
        $model->save($data);

        // 将微信用户昵称添加编号便于后台管理, 例如：微信用户_10001
        $model->save(['nick_name' => "微信用户_{$model['id']}"]);

        // 记录用户信息
        $this->userInfo = $model;
    }
    /**
     * 更新用户登录信息
     * @param UserModel $userInfo
     * @param bool $isParty 是否存在第三方用户信息
     * @param array $partyData 用户信息(第三方)
     * @throws BaseException
     * @throws \think\Exception
     */
    private function updateUser(UserModel $userInfo): void
    {
        // 用户信息
        $data = [
            'login_time' => time()
        ];

        // 更新用户记录
        $userInfo->save($data);
        // 记录用户信息
        $this->userInfo = $userInfo;
    }


    private function prepareCachedValue($wxResult, $uid){
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        return $cachedValue;
    }

    // 写入缓存
    private function saveToCache($wxResult){
        $key = self::generateToken();
        $value = json_encode($wxResult);
        $expire_in = $this->token_expire_in;
        $result = cache($key, $value, $expire_in);

        if (!$result){
            return throwError('服务器缓存异常', 10005);
        }
        return $key;
    }


    /**
     *  生成令牌
     * @return string
     */
    private static function generateToken(){
        $randChar = getRandChar(32);
        $timestamp = $_SERVER["REQUEST_TIME_FLOAT"];
        $tokenSalt = self::TOKEN_SALT;
        return md5($randChar . $timestamp . $tokenSalt);
    }


}